package com.darren.euc.service.impl;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.darren.euc.dao.BillDao;
import com.darren.euc.dao.BillDetailDao;
import com.darren.euc.entity.Bill;
import com.darren.euc.entity.BillDetail;
import com.darren.euc.entity.PageBean;
import com.darren.euc.service.BillService;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;


@Service
public class BillServiceImpl implements BillService {

    private static final Logger log = Logger.getLogger(BillServiceImpl.class);

    @Autowired
    private BillDao billDao;

    @Autowired
    private BillDetailDao billDetailDao;


    @Override
	public Bill save(Bill bill) {
		for (BillDetail billDetail : bill.getBillDetails()) {
			if (billDetail.getId() == null) {
				billDetailDao.save(billDetail);
			} else {
				billDetailDao.update(billDetail);
			}
		}
		bill = billDao.save(bill);
		for (BillDetail billDetail : bill.getBillDetails()) {
			billDetail.setBill(bill);
			billDetailDao.update(billDetail);
		}
		return bill;
	}

	@Override
	public Bill update(Bill bill) {
		for (BillDetail billDetail : bill.getBillDetails()) {
			billDetail.setBill(bill);
			if (billDetail.getId() == null) {
				billDetailDao.save(billDetail);
			} else {
				billDetailDao.update(billDetail);
			}
		}
		bill.setBillStatus(bill.getBillStatus());
		bill = billDao.update(bill);
		billDao.updateRoomOrderHirePurchase(bill.getId());
		billDao.updateOtherOrder(bill.getId());
		return bill;
	}

	@Override
	public void delete(Bill bill) {
		for (BillDetail billDetail : bill.getBillDetails()) {
			billDetailDao.delete(billDetail);
		}
		billDao.delete(bill);
	}
	
	@Override
	public BillDetail saveBillDetail(BillDetail billDetail){
		return billDetailDao.save(billDetail);
	}
	
	@Override
	public BillDetail updateBillDetail(BillDetail billDetail){
		return billDetailDao.update(billDetail);
	}
	
	@Override
	public void deleteBillDetail(Integer billDetailId){
		BillDetail billDetail = billDetailDao.findById(billDetailId);
		billDetailDao.delete(billDetail);
	}

    @Override
    public List<Bill> getAll() {
        return billDao.getAll();
    }
    
    @Override
    public void generateBillData(){
    	billDao.generateBillData();	
    }
	
    @Override
	public void updateBillStatus(){
    	billDao.updateBillStatus();
    }

    @SuppressWarnings("rawtypes")
    public PageBean queryForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){
        String HQL = null;
        String likes = null;
        String equals = null;
        List<Object> parameters = new ArrayList<Object>();
        Integer clientId =0;
        try{
            clientId = requestJson.getInt("clientId");
        }catch(Exception e){
            e.printStackTrace();
            clientId =0;
        }
        JSONObject likeJson = requestJson.getJSONObject("like");
        Iterator likeIterator = likeJson.keys();
        while(likeIterator.hasNext()){
            String key = (String) likeIterator.next();
            key = StringUtil.convertNullToEmptyString(key);
            String value = likeJson.getString(key);
            value = StringUtil.convertNullToEmptyString(value);
            if(!"".equals(value)){
                likes = (likes == null?"": likes + " OR ") +  key + " like ? ";
                parameters.add("%"+value+"%");
            }
        }
        HQL = likes == null?null:(" (" + likes + ") ");
        JSONObject equalsJson = requestJson.getJSONObject("equals");
        Iterator equalsIterator = equalsJson.keys();
        while(equalsIterator.hasNext()){
            String key = (String) equalsIterator.next();
            key = StringUtil.convertNullToEmptyString(key);
            String value = equalsJson.getString(key);
            value = StringUtil.convertNullToEmptyString(value);
            if(!"".equals(value)){
                if("dateStart".equals(key)){
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date startDate = (Date)format.parse(value);
                        parameters.add(startDate);
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                    equals = (equals == null?"": ""+equals + " and ") +  " billDate >= ? ";
                }else if("dateEnd".equals(key)){
                    DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date endDate = (Date)format.parse(value + " 23:59:59 ");
                        Calendar calendar = Calendar.getInstance();
                        calendar.setTime(endDate);
                        int day=calendar.get(Calendar.DATE);
                        calendar.set(Calendar.DATE,day);
                        parameters.add(calendar.getTime());
                    } catch (ParseException e) {
                        log.error(e.getMessage(),e);
                    }
                    equals = (equals == null?"": ""+equals + " and ") +  " billDate <= ? ";
                }else if("spaceId".equals(key)){
                    equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
                    parameters.add(Integer.parseInt(value));
                }else if("billStatus".equals(key)){
                    equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
                    parameters.add(Integer.parseInt(value));
                }else{
                    equals = (equals == null?"": ""+equals + " and ") +  key + " = ? ";
                    parameters.add(value);
                }
            }
        }
        if(HQL != null){
            if(equals != null){
                HQL = HQL + " and " + equals;
            }
        }else{
            HQL = equals;
        }
        String clientCondition = "";
        if(clientId>0){
                 clientCondition  =" and clientId = "+clientId+" ";
        }
        Object order = requestJson.get("order");
        if(order != null){
        	HQL = "from Bill where 1 = 1 " + (HQL == null?"  ":"   and " + HQL) +clientCondition +" order by " + order.toString();
        }else{
        	HQL = "from Bill where 1 = 1 " + (HQL == null?"  ":"   and " + HQL) +clientCondition +" order by billDate asc ";
        }
        return billDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
    }


}